<template>
  <div class="app-container" :style="height">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px" class="work-search-form">
      <el-form-item label="标题" prop="contentTitle">
        <el-input v-model="form.contentTitle" placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="栏目" prop="contentType">
        <treeselect v-model="form.contentType"
                    :options="typeOptions"
                    :disable-branch-nodes="true"
                    :show-count="true"
                    placeholder="请选择栏目" />
      </el-form-item>
      <el-form-item label="来源" prop="contentSource">
        <el-input v-model="form.contentSource" placeholder="请输入来源" />
      </el-form-item>
      <el-form-item label="作者" prop="contentAuthor">
        <el-input v-model="form.contentAuthor" placeholder="请输入作者" />
      </el-form-item>
      <el-form-item label="编辑" prop="contentEditor">
        <el-input v-model="form.contentEditor" placeholder="请输入编辑" />
      </el-form-item>
      <el-form-item label="内容" prop="contentContent">
        <Editor v-model="form.contentContent" style="height: 240px;" />
      </el-form-item>
      <div>
        <el-form-item label="视频地址">
          <el-upload
            ref="upload"
            accept=".wmv, .mp4"
            :action="upload.url"
            :headers="upload.headers"
            :show-file-list="true"
            :limit="1"
            :on-exceed="handleFileExceed"
            :on-success="handleFileSuccess"
            :before-upload="beforeAvatarUpload">
            <el-button slot="trigger" size="small" type="primary">上传视频文件</el-button>
            <el-button size="small" type="primary" style="float: right" @click="openWin()">选择标准模板</el-button>
            <div slot="tip" class="el-upload__tip">如果内容中需要添加视频，请先通过上传视频获取视频地址，复制后通过文本编辑器插入即可！(只能上传.WMV, .mp4格式的视频)</div>
          </el-upload>
        </el-form-item>
      </div>
      <el-form-item label="接收人">
        <el-tree
          :data="menuOptions"
          show-checkbox
          ref="menu"
          node-key="id"
          empty-text="加载中，请稍后"
          :props="defaultProps"
        ></el-tree>
        <div slot="tip" class="el-upload__tip">可多选，未指定为对所有人公开</div>
      </el-form-item>
      <el-form-item label="上传附件">
        <el-upload
          ref="upload"
          accept=".bmp, .gif, .jpg, .jpeg, .png, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .html, .htm, .txt, .rar, .zip, .gz, .bz2, .pdf, .mp4, .wmv"
          :action="upload.url"
          :headers="upload.headers"
          multiple
          :file-list="upload.fileList"
          :on-success="annexSuccess"
          :on-remove="annexRemove"
          :before-upload="beforeAvatarUpload">
          <el-button slot="trigger" size="small" type="primary">上传附件</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align:center">
      <el-button type="primary" @click="submitForm('0')">发 布</el-button>
      <el-button type="primary" @click="submitForm('3')">提 交</el-button>
      <el-button type="primary" @click="submitForm('1')">保 存</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>

    <el-dialog width="40%" title="选择标准模板" :visible.sync="innerVisible" append-to-body>
      <div>
        <el-table :data="templateList" v-loading="loading" ref="multipleTable" @selection-change="handleSelectionChange" highlight-current-row >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="标题" align="center" prop="templateName" />
          <el-table-column label="内容" align="center" prop="templateContent" :show-overflow-tooltip="true" />
          <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" />
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button type="primary" @click="saveTemplate">确 定</el-button>
        <el-button @click="cancelDialog">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {addContent, updateContent, treeselect, treeselectColumn } from "@/api/system/content";
  import Editor from '@/components/Editor';
  import { getToken } from "@/utils/auth";
  import { listTemplate } from "@/api/system/template";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";

  export default {
    name: "addEditContent",
    components: {
      Editor,Treeselect
    },
    data() {
      return {
        height:"max-height:"+((document.documentElement.clientHeight||document.body.clientHeight)-110)+"px;overflow-y:auto",

        // 遮罩层
        loading: true,
        form: {},
        // 类型数据字典
        typeOptions: [],
        // 状态数据字典
        statusOptions: [],
        // 接受人员部门列表
        menuOptions: [],

        //tab选中数据
        multipleSelection: [],

        defaultProps: {
          children: "children",
          label: "label"
        },
        // 是否显示内弹出层
        innerVisible: false,
        // 栏目内容表格数据
        templateList: [],
        // 总条数
        total: 0,
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          templateName: null,
          templateContent: null,
          status: null,
          createName: null,
          updateName: null,
          remake: null
        },
        // 表单校验
        rules: {
          contentTitle: [
            { required: true, message: "标题不能为空", trigger: "blur" }
          ],
          contentType: [
            { required: true, message: "栏目不能为空", trigger: "blur" }
          ],
          contentContent: [
            { required: true, message: "内容不能为空", trigger: "blur" }
          ],
        },
        upload: {
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/common/upload",
          // 上传的文件列表
          fileList: []
        },
      }
    },
    created() {
      this.reset();
      const row = this.$route.params && this.$route.params.row;
      this.getTreeselect();
      this.getDicts("t_column_content_status").then(response => {
        this.statusOptions = response.data;
      });
      this.getMenuTreeselect();
      if (row!=null && row!=undefined && row!=''){
        this.form = row;
        this.form.contentType = ''+this.form.contentType+'';
        this.$nextTick(() => {
          const arr = [];
          if (this.form.receiveUserId != null){
            var userids = this.form.receiveUserId.split(",");
            for (var k=0;k<userids.length;k++){
              arr.push(parseInt(userids[k]));
            }
          }
          this.$refs.menu.setCheckedKeys(userids);//获取已经设置的资源后渲染
        });
        this.$nextTick(() => {
          const arr = [];
          if (row.attachmentName != null){
            var attachmentName = row.attachmentName.split(",");
            var attachmentUrl = row.attachmentUrl.split(",");
            var attachmentPath = row.attachmentPath.split(",");
            for (var k=0;k<attachmentName.length;k++){
              arr.push({
                name:attachmentName[k],
                response:{
                  fileName:attachmentPath[k],
                  url:attachmentUrl[k],
                }
              });
            }
          }
          this.upload.fileList=arr;
          this.form.fileList=arr;
        });
      }
    },
    methods: {
      // 表单重置
      reset() {
        if (this.$refs.menu != undefined) {
          this.$refs.menu.setCheckedKeys([]);
        }
        this.form = {
          contentId: null,
          contentTitle: null,
          contentType: null,
          contentSource: '',
          contentAuthor: '',
          contentEditor: '',
          contentContent: null,
          issueDepartmentId: null,
          issueUserId: null,
          issueTime: null,
          receiveUserId: null,
          receiveDepartmentId: null,
          status: "0",
          istop: null,
          createName: null,
          updateName: null,
          updateTime: null,
          remake: null,
          fileList: [],
          menuIds: [],
        };
        this.upload.fileList = [];
        this.resetForm("form");
      },
      // 取消按钮
      cancel() {
        this.$router.go(-1);// 返回
        //关闭子页面
        this.$store.state.tagsView.visitedViews.splice(this.$store.state.tagsView.visitedViews.findIndex(item => item.path === this.$route.path), 1);
        var view = {
          name: 'Content',
        }
        this.$store.dispatch('tagsView/delView', view).then(({ visitedViews }) => {
          this.$router.push(this.$store.state.tagsView.visitedViews[this.$store.state.tagsView.visitedViews.length - 1].path);
        })
      },
      //弹框取消
      cancelDialog(){
        this.innerVisible = false;
      },
      /** 提交按钮 */
      submitForm:function(statu) {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.contentId != null) {
              this.form.status = statu;
              this.form.menuIds = this.getMenuAllCheckedKeys();
              updateContent(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.cancel();
                }
              });
            } else {
              this.form.status = statu;
              this.form.menuIds = this.getMenuAllCheckedKeys();
              addContent(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.cancel();
                }
              });
            }
          }
        });
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.msgSuccess(response.msg);
        this.$alert(response.url, '视频地址', {
          dangerouslyUseHTMLString: true
        });
      },
      // 超过上传限制
      handleFileExceed(files, fileList){
        this.$alert('超出上传数量限制，请删除后继续上传！', '超出数量限制', {
          dangerouslyUseHTMLString: true
        });
      },
      // 附件上传成功处理
      annexSuccess(response, file, fileList) {
        this.form.fileList=fileList
      },
      // 附件上传失败处理
      annexRemove(file, fileList) {
        this.form.fileList=fileList
      },
      //附件上传前检测
      beforeAvatarUpload(file) {
        const fileAllowd = ['bmp', 'gif', 'jpg', 'jpeg', 'png', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'html', 'htm', 'txt', 'rar', 'zip', 'gz', 'bz2', 'pdf', 'mp4', 'wmv'];
        const isFileAllowd = fileAllowd.indexOf(file.name.substring(file.name.lastIndexOf('.') + 1)) === -1;
        if (isFileAllowd) {
          this.msgError('上传文件格式不允许!');
        }
        const isfileSize = file.size / 1024 / 1024 < 500;
        if (!isfileSize) {
          this.msgError('上传文件大小不能超过500MB!');
        }
        return isfileSize&&!isFileAllowd;
      },
      /** 查询菜单树结构 */
      getMenuTreeselect() {
        treeselect().then(response => {
          this.menuOptions = response.data;
        });
      },
      // 所有人员节点数据
      getMenuAllCheckedKeys() {
        // 目前被选中的菜单节点
        let checkedKeys = this.$refs.menu.getHalfCheckedKeys();
        // 半选中的菜单节点
        let halfCheckedKeys = this.$refs.menu.getCheckedKeys();
        checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
        return checkedKeys;
      },
      // 类型字典翻译
      typeFormat(row, column) {
        return this.selectDictLabel(this.typeOptions, row.contentType);
      },
      // 状态字典翻译
      statusFormat(row, column) {
        return this.selectDictLabel(this.statusOptions, row.status);
      },
      openWin(){
        this.getList();
        this.innerVisible = true;
      },
      saveTemplate(){
        this.form.contentContent = this.multipleSelection.templateContent;
        this.innerVisible = false;
      },
      /** 查询标准模板列表 */
      getList() {
        this.loading = true;
        listTemplate(this.queryParams).then(response => {
          this.templateList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      handleSelectionChange(selection) {
        if (selection.length>1){
          this.$refs.multipleTable.clearSelection();
          this.$refs.multipleTable.toggleRowSelection(selection.pop());
        }else {
          this.multipleSelection = selection.pop();
        }
      },
      /**查询栏目下拉树**/
      getTreeselect() {
        var params = { status: 0 };
        treeselectColumn(params).then(response => {
          this.typeOptions = response.data;
        });
      },
    }
  }
</script>
